package controllers;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import services.OperatorService;
import services.RoleUserService;
import utils.BizConstants;
import vos.OperatorSearchVo;
import vos.ResultVo;
import vos.ReturnCode;
import vos.ReturnListVo;
import models.Operator;
import models.Oplog;
import models.Role;

public class RoleUserController extends BaseController {
	/**
	 * 跳转到用户角色分配页面
	 *
	 * @Title: roleUser 
	 * @return: void
	 */
	public static void roleUser(){
		render();
	}
	/**
	 * 获取角色列表
	 *
	 * @Title: getRole 
	 * @return: void
	 */
	public static void getRole(){
		List<Role> roles=RoleUserService.getRole();
		renderJSON(roles);
	}
	/**
	 * 获取操作员列表
	 *
	 * @Title: getOperator 
	 * @return: void
	 */
	public static void getUseOperator(String sort,String order,String operatorname,
			String operatorid,Boolean isflag,String roleid){
		OperatorSearchVo vo =new OperatorSearchVo(order,sort,operatorname,operatorid,isflag,roleid);
		long total=OperatorService.countUseOperator(vo);
		ReturnListVo listVo=new ReturnListVo();
		listVo.setTotal(total);
		List<Operator> lists=OperatorService.listUseOperator(vo);
		listVo.setRows(lists);
		renderJSON(listVo);
	}
	/**
	 * 根据角色获取角色用户
	 *
	 * @Title: getRoleOperator 
	 * @param roleid
	 * @return: void
	 */
	public static void getRoleOperator(String roleid){
		if(StringUtils.isEmpty(roleid)){
			renderFailedJson(ReturnCode.ErrorCode,"请选择角色");
		}
		List<String> list=RoleUserService.getRoleOperator(roleid);
		ResultVo vo=new ResultVo(list);
		renderJSON(vo);
	}
	/**
	 * 保存角色用户数据
	 *
	 * @Title: saveRoleUser 
	 * @param roleid 角色id
	 * @param ids 用户id数组
	 * @return: void
	 */
	public static void saveRoleUser(String roleid,String ids){
		if(StringUtils.isEmpty(roleid)){
			renderFailedJson(ReturnCode.ErrorCode,"请选择角色");
		}
		Set<String> operList=new HashSet<String>();
		if(StringUtils.isNotEmpty(ids)){
			String[] operids=ids.split(",");
			Collections.addAll(operList, operids);
		}
		else{
			operList=null;
		}
		boolean isok=RoleUserService.saveRoleUser(roleid,operList);
		if(isok){
			Operator oper=getLoginUser();
			Oplog oplog=new Oplog(oper.operatorid,"为角色"+roleid+"添加用户："+ids,"角色用户管理");
			oplog.save(oplog);
			renderFailedJson(ReturnCode.SuccessCode,"保存成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"保存失败");
		}
	}
}
